package com.example.musicplay

import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.IBinder
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity(), ServiceConnection {
    val TAG = "MainActivity"
    var binder: MusicService.MusicBinder? = null // 音乐服务的绑定器

    val Channel_ID = "my channel"  // 通知渠道 ID
    val Notification_ID = 1        // 通知 ID

    @SuppressLint("MissingInflatedId")
    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_main)    // 设置布局文件

        // 获取通知按钮并设置点击监听器
        val button_notification = findViewById<Button>(R.id.notice)
        button_notification.setOnClickListener {
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val builder: Notification.Builder

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val notificationChannel = NotificationChannel(Channel_ID, "My Notification", NotificationManager.IMPORTANCE_DEFAULT)
                notificationManager.createNotificationChannel(notificationChannel)
                builder = Notification.Builder(this, Channel_ID)
            } else {
                builder = Notification.Builder(this) // 使用默认构造器
            }

            val intent = Intent(this, MainActivity::class.java)
            val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
            // 构建通知
            val textView_mn = findViewById<TextView>(R.id.textView_musicname)
            val notification = builder.setSmallIcon(R.drawable.ic_notification)
                .setContentTitle("Music Application")
                .setContentText("正在播放 ${textView_mn.text.toString()}")
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .build()

            notificationManager.notify(Notification_ID, notification) // 显示通知
        }

        // 请求权限以读取媒体
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_MEDIA_AUDIO), 0)
        } else {
            startMusicService() // 开始音乐服务
        }

        // 设置 SeekBar 的变化监听器
        val seekBar = findViewById<SeekBar>(R.id.seekBar)
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                if (fromUser) { // 仅当用户拖动 SeekBar 时更新当前播放位置
                    binder?.currentPosition = progress
                }
            }
            override fun onStartTrackingTouch(seekBar: SeekBar) {} // 开始拖动
            override fun onStopTrackingTouch(seekBar: SeekBar) {} // 停止拖动
        })
    }



    // 启动音乐服务
    fun startMusicService() {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 1) // 发送命令给服务
        startService(intent) // 启动服务
        bindService(intent, this, Context.BIND_AUTO_CREATE) // 绑定服务
    }

    // 播放音乐
    fun onPlay(view: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 1)
        startService(intent) // 启动服务
    }

    // 暂停音乐
    fun onPause(view: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 2)
        startService(intent)
    }

    // 停止音乐
    fun onStop(view: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 3)
        startService(intent)
    }

    // 下一曲
    fun onNext(view: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 4)
        startService(intent)
    }

    // 上一曲
    fun onPrev(view: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 5)
        startService(intent)
    }

    // 请求权限结果的回调
    private fun onRequestPermissionResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        startMusicService() // 启动音乐服务
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(this) // 解绑服务
    }

    @SuppressLint("SetTextI18n")
    override fun onServiceConnected(p0: ComponentName?, service: IBinder?) {
        binder = service as MusicService.MusicBinder // 绑定服务
        thread { // 在新线程中更新 UI
            while (binder != null) {
                Thread.sleep(1000) // 每秒更新一次
                runOnUiThread { // 在主线程中更新 UI
                    val seekBar = findViewById<SeekBar>(R.id.seekBar)
                    seekBar.max = binder!!.duration // 设置 SeekBar 最大值
                    seekBar.progress = binder!!.currentPosition // 更新 SeekBar 当前进度
                    val textView_mn = findViewById<TextView>(R.id.textView_musicname)
                    val textView_count = findViewById<TextView>(R.id.textView_count)
                    textView_mn.text = binder!!.musicName // 更新音乐名称
                    textView_count.text = "${binder!!.currentIndex + 1} / ${binder?.size}" // 更新音乐索引
                }
            }
        }
    }

    override fun onServiceDisconnected(p0: ComponentName?) {
        binder = null // 服务断开连接
    }
}



